package com.android.basiclib.base;

import android.app.Activity;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;


import java.lang.reflect.InvocationTargetException;


/**
 * 用于反射构建双参的ViewModel实例
 */
public class AutoViewModelFactory extends ViewModelProvider.NewInstanceFactory {
    private Activity mActivity;


    public AutoViewModelFactory(Activity activity) {
        mActivity = activity;
    }


    @Override
    public <T extends ViewModel> T create(Class<T> modelClass) {
        //使用了反射，需要混淆BaseViewModel的全部继承类
        try {
            return modelClass.getConstructor(Activity.class).newInstance(mActivity);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return super.create(modelClass);
    }
}
